<template>
  <DetailsFormBox :title="dataInfo?.table?.title" :type="data.type" :form="data.form" :btns="[
    {
      title: '重置',
      icon: '',
      type: '',
      click: getForm,
    },
    {
      title: '保存',
      icon: '',
      type: 'primary',
      click: (form: any) => {
        saveBtn(form)
      },
    },
  ]" :loading="data.loading" :json="dataInfo">
    <template #default="{ form }">
      <div class="m-16">
        <CellBox title="基础信息" isTop>
          <FlexBox :list="3">
            <ElFormItemBox label="员工工号" :prop="`employeeWorkNo`">
              <ElInputBox :data="form.machineCode" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="员工姓名" :prop="`employeeName`" isRules>
              <ElInputBox :data="form" dataName="employeeName" />
            </ElFormItemBox>
            <ElFormItemBox label="手机号" :prop="`mobile`" isRules :rules="[
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
            ]">
              <ElInputBox :data="form" dataName="mobile" />
            </ElFormItemBox>
            <ElFormItemBox label="所属部门" :prop="`departmentCode`" isRules>
              <ElSelectBox :data="form" dataName="departmentCode" :options="dataInfo.tabs.list"
                :labelName="dataInfo.tabs.titleKey" :valueName="dataInfo.tabs.activeKey" />
            </ElFormItemBox>
            <ElFormItemBox label="员工角色" :prop="`roleCode`" isRules>
              <ElSelectBox :data="form" dataName="roleCode" :options="options.roles" />
            </ElFormItemBox>
            <ElFormItemBox label="员工备注" :prop="`employeeRemark`" class="wAuto">
              <ElInputBox :data="form" dataName="employeeRemark" type="textarea" />
            </ElFormItemBox>
          </FlexBox>
        </CellBox>
        <CellBox title="工作信息" isTop>
          <FlexBox :list="3">
            <ElFormItemBox label="员工类型" :prop="`employeeType`">
              <ElSelectBox :data="form" dataName="employeeType" :options="options.employeeType" />
            </ElFormItemBox>
            <ElFormItemBox label="入职日期" :prop="`hiredate`">
              <ElDayBox :data="form" dataName="hiredate" />
            </ElFormItemBox>
            <ElFormItemBox label="员工状态" :prop="`employeeState`">
              <ElSelectBox :data="form" dataName="employeeState" :options="options.employeeState" />
            </ElFormItemBox>
            <ElFormItemBox label="试用期" :prop="`probation`">
              <ElInputBox :data="form" dataName="probation" unit="月" />
            </ElFormItemBox>
            <ElFormItemBox label="计划转正日期" :prop="`planPositiveTime`">
              <ElDayBox :data="form" dataName="planPositiveTime" />
            </ElFormItemBox>
            <ElFormItemBox label="实际转正日期" :prop="`positiveTime`">
              <ElDayBox :data="form" dataName="positiveTime" />
            </ElFormItemBox>
            <ElFormItemBox label="岗位职级" :prop="`employeeRank`">
              <ElInputBox :data="form" dataName="employeeRank" />
            </ElFormItemBox>
          </FlexBox>
        </CellBox>
        <CellBox title="个人信息" isTop>
          <FlexBox :list="3">
            <ElFormItemBox label="证件号码" :prop="`idCardNo`">
              <ElInputBox :data="form" dataName="idCardNo" @changeBtn="changeIdCard" />
            </ElFormItemBox>
            <ElFormItemBox label="证件有效期" :prop="`certificateValidity`">
              <ElDayBox :data="form" dataName="certificateValidity" />
            </ElFormItemBox>
            <ElFormItemBox label="出生日期" :prop="`birthday`">
              <ElDayBox :data="form" dataName="birthday" />
            </ElFormItemBox>
            <ElFormItemBox label="年龄" :prop="`age`">
              <ElInputBox :data="getear(form.birthday)" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="员工性别" :prop="`employeeSex`">
              <ElSelectBox :data="form" dataName="employeeSex" :options="proxy.$optionsArr.sex" />
            </ElFormItemBox>
            <ElFormItemBox label="民族" :prop="`nation`">
              <ElSelectBox :data="form" dataName="nation" :options="options.nation" />
            </ElFormItemBox>
            <ElFormItemBox label="现居住地址" :prop="`currentAddress`">
              <ElInputBox :data="form" dataName="currentAddress" />
            </ElFormItemBox>
            <ElFormItemBox label="身份证地址" :prop="`homeAddress`">
              <ElInputBox :data="form" dataName="homeAddress" />
            </ElFormItemBox>
            <ElFormItemBox label="户籍类型" :prop="`huJi`">
              <ElSelectBox :data="form" dataName="huJi" :options="options.residenceType" />
            </ElFormItemBox>
            <ElFormItemBox label="政治面貌" :prop="`politicsStatus`">
              <ElSelectBox :data="form" dataName="politicsStatus" :options="options.politicsStatus" />
            </ElFormItemBox>
            <ElFormItemBox label="婚姻状况" :prop="`maritalStatus`">
              <ElSelectBox :data="form" dataName="maritalStatus" :options="options.maritalStatus" />
            </ElFormItemBox>
          </FlexBox>
        </CellBox>
        <CellBox title="社保信息" isTop>
          <FlexBox :list="3">
            <ElFormItemBox label="首次参加工作时间" :prop="`beginWorkTime`">
              <ElDayBox :data="form" dataName="beginWorkTime" />
            </ElFormItemBox>
            <ElFormItemBox label="工龄" :prop="`workAge`">
              <ElInputBox :data="getear(form.beginWorkTime)" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="个人社保账户" :prop="`socialSecurityAccount`">
              <ElInputBox :data="form" dataName="socialSecurityAccount" />
            </ElFormItemBox>
            <ElFormItemBox label="个人公积金账户" :prop="`providentFundAccount`">
              <ElInputBox :data="form" dataName="providentFundAccount" />
            </ElFormItemBox>
          </FlexBox>
        </CellBox>
        <CellBox title="银行卡信息" isTop>
          <FlexBox :list="3">
            <ElFormItemBox label="银行卡号" :prop="`bankCardNo`">
              <ElInputBox :data="form" dataName="bankCardNo" />
            </ElFormItemBox>
            <ElFormItemBox label="开户行" :prop="`bankAddress`">
              <ElInputBox :data="form" dataName="bankAddress" />
            </ElFormItemBox>
          </FlexBox>
        </CellBox>
        <CellBox title="合同信息" isTop>
          <FlexBox :list="3">
            <ElFormItemBox label="合同期限" :prop="`contractPeriod`">
              <ElNumberBox :data="form" dataName="contractPeriod" unit="年" />
            </ElFormItemBox>
            <ElFormItemBox label="首次合同起始日" :prop="`contractSignedDate`">
              <ElDayBox :data="form" dataName="contractSignedDate" @changeBtn="(value: string) => {
                form.contractExpirationDate = proxy.$getTimeAgo(-form.contractPeriod, 'years', value)
              }" />
            </ElFormItemBox>
            <ElFormItemBox label="首次合同到期日" :prop="`contractExpirationDate`">
              <ElDayBox :data="form" dataName="contractExpirationDate" />
            </ElFormItemBox>
            <ElFormItemBox label="现合同起始日" :prop="`nowContractSignedDate`">
              <ElDayBox :data="form" dataName="nowContractSignedDate" @changeBtn="(value: any) => {
                form.nowContractExpirationDate = proxy.$getTimeAgo(-form.contractPeriod, 'years', value)
                if (form.contractSignedDate) {
                  const YearDifference = proxy.$getYearDifference(form.contractSignedDate, value)
                  console.log(YearDifference);
                  if (YearDifference > Number(form.contractPeriod)) {
                    form.renewalTimes = Math.floor(YearDifference / form.contractPeriod) - 1
                  }
                }

              }" />
            </ElFormItemBox>
            <ElFormItemBox label="现合同到期日" :prop="`nowContractExpirationDate`">
              <ElDayBox :data="form" dataName="nowContractExpirationDate" />
            </ElFormItemBox>
            <ElFormItemBox label="续签次数" :prop="`renewalTimes`">
              <ElNumberBox :data="form" dataName="renewalTimes" unit="次" />
            </ElFormItemBox>
          </FlexBox>
        </CellBox>
        <CellBox title="学历信息" isTop>
          <TableBoxMx :data="{
            tbody: form.educationList,
            thead: [
              {
                label: '学历',
                prop: 'educationCode',
                align: 'center',
                width: 160,
                formType: 'select', //文件类型
                options: options.qualification,
              },
              {
                label: '毕业院校',
                prop: 'school',
                align: 'center',
                width: 220,
                formType: 'text', //文件类型
              },
              {
                label: '毕业时间',
                prop: 'graduationTime',
                align: 'center',
                width: 160,
                formType: 'day', //文件类型
              },
              {
                label: '所学专业',
                prop: 'major',
                align: 'center',
                width: null,
                formType: 'text', //文件类型
              },
            ],
            //操作
            operation: [
              {
                label: '删除',
                icon: 'Delete',
              }
            ],
            add: {
              employeeEducationID: 0, // 学历信息主键ID
              employeeCode: '', // 员工编码
              educationCode: '', // 学历编码（关联字典表）
              school: '', // 毕业院校
              graduationTime: '', // 毕业时间
              major: '' // 所学专业
            }
          }">
          </TableBoxMx>
        </CellBox>
        <CellBox title="紧急联系人" isTop>
          <TableBoxMx :data="{
            tbody: form.contactList,
            thead: [
              {
                label: '联系人姓名',
                prop: 'contactName',
                align: 'center',
                width: 160,
                formType: 'text', //文件类型
              },
              {
                label: '联系人关系',
                prop: 'contactRelationship',
                align: 'center',
                width: 160,
                formType: 'text', //文件类型
              },
              {
                label: '联系人电话',
                prop: 'contactPhone',
                align: 'center',
                width: 200,
                formType: 'text', //文件类型
              },
              {
                label: '备注',
                prop: 'remark',
                align: 'center',
                width: null,
                formType: 'text', //文件类型
              },
            ],
            //操作
            operation: [
              {
                label: '删除',
                icon: 'Delete',
              }
            ],
            add: {
              employeeEducationID: 0, // 学历信息主键ID
              employeeCode: '', // 员工编码
              educationCode: '', // 学历编码（关联字典表）
              school: '', // 毕业院校
              graduationTime: '', // 毕业时间
              major: '' // 所学专业
            }
          }">
          </TableBoxMx>
        </CellBox>
        <CellBox title="文件材料" isTop>
          <FlexBox :list="3">
            <ElFormItemBox :label="item.title" v-for="item in form.fileDataList">
              <dl class="flex list-r-12">
                <dt>
                  <ElImgBox :data="item" urlKey="filePreviewUrl" :width="160" :height="160" />
                </dt>
                <dd class="list-b-2">
                  <ElUploadBox type="img" @changeBtn="(files: any, dataInfo: any, res: any) => {
                    item.filePreviewUrl = res.fileUrl
                    item.fileOriginalName = res.fileName
                    item.fileUrl = res.fileUrl
                    dataInfo.loading = false
                  }" :accept="['.jpg', '.jpeg', '.png', '.gif']" />
                  <p class="text-color-info f-12">上传图片只能是JPG/PNG格式,不能超过5MB</p>
                </dd>
              </dl>
            </ElFormItemBox>
          </FlexBox>
        </CellBox>
      </div>
    </template>
  </DetailsFormBox>
</template>
<script setup lang="ts">
import { useListComponent } from '../pageTs'; // 引入逻辑
const { dataInfo, options } = useListComponent();
import { reactive, onMounted, getCurrentInstance } from 'vue';
const { proxy } = getCurrentInstance() as any;
const data = reactive({
  loading: false,
  loadingMsg: '',
  type: '2',
  form: {
    employeeID: 0, // 员工主键ID
    employeeCode: "", // 员工代码（唯一识别码，工号）
    accountState: 1, // 账户状态：0未启用；1可用（已启用）；2禁用
    employeeName: "", // 员工姓名
    roleCode: "", // 角色编码
    roleName: "", // 角色名称
    employeeSex: 1, // 员工性别：1表示男；2表示女
    idCardNo: "", // 身份证号
    birthday: "", // 出生日期
    mobile: "", // 手机号码
    nation: "", // 所属民族（外联字典明细表唯一识别码）
    homeAddress: "", // 身份证地址
    currentAddress: "", // 现居住地址
    email: "", // Email地址
    employeeState: "", // 员工状态（外联字典明细表唯一识别码）
    hiredate: "", // 入职时间
    departmentCode: "", // 部门编码
    departmentName: "", // 部门名称
    probation: 0, // 试用期（单位：月）
    positiveTime: "", // 实际转正时间
    createBy: "", // 创建人员编码
    createByName: "", // 创建人员名称
    createDate: "", // 创建时间
    modifyBy: "", // 修改人员编码
    modifyByName: "", // 修改人员名称
    modifyDate: "", // 修改时间
    maritalStatus: "", // 婚姻状况（外联字典明细表唯一识别码）
    politicsStatus: "", // 政治面貌（外联字典明细表唯一识别码）
    beginWorkTime: "", // 首次参加工作时间
    isDelete: 0, // 是否删除：0否；1是(目前当作禁用状态使用)
    contractSignedDate: "", // 首次合同签订日期
    contractExpirationDate: "", // 首次合同到期日期
    employeeRemark: "", // 员工备注
    huJi: "", // 户籍类型
    employeeType: "", // 员工类型（关联字典表）
    planPositiveTime: "", // 计划转正日期
    employeeRank: "", // 员工职级
    certificateValidity: "", // 证件有效期
    socialSecurityAccount: "", // 社保账户
    providentFundAccount: "", // 公积金账户
    bankCardNo: "", // 银行卡号
    bankAddress: "", // 开户行地址
    nowContractSignedDate: "", // 现合同起始日期
    nowContractExpirationDate: "", // 现合同到期日期
    contractPeriod: 0, // 合同期限
    renewalTimes: 0, // 续签次数
    employeeWorkNo: "", // 员工工号
    educationList: [
      {
        employeeEducationID: 0, // 学历信息主键ID
        employeeCode: "", // 员工编码
        educationCode: "", // 学历编码（关联字典表）
        school: "", // 毕业院校
        graduationTime: "", // 毕业时间
        major: "" // 所学专业
      }
    ],
    contactList: [
      {
        employeeEmergencyContactID: 0, // 紧急联系人信息主键ID
        employeeCode: "", // 员工编码
        contactName: "", // 联系人姓名
        contactRelationship: "", // 与联系人关系
        contactPhone: "", // 联系电话
        remark: "" // 备注
      }
    ],
    fileDataList: []
  },
});
import { useRoute } from 'vue-router';
// 获取当前路由对象
const route = useRoute();
import { sendMsg } from '@/utils/crossTagMag.ts';
// 校验身份证最后一位校验码
const changeIdCard = (value: string) => {
  let _form: any = data.form
  // 身份证正则表达式验证规则（18位）
  const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/;
  if (!idCardRegex.test(value)) {
    proxy.$message('身份证号格式不正确', 'error');
    sun()
    return false;
  }

  // 进一步验证第18位校验码（可选）
  if (!checkIdCardChecksum(value)) {
    proxy.$message('身份证号校验码不正确', 'error');
    sun()
    return false;
  }

  const IdInfo = getIdInfo(value)
  if (IdInfo.isValid) {
    _form.birthday = IdInfo.birthDate
    _form.employeeSex = IdInfo.gender
  }
  function sun() {
    _form.idCardNo = ''
    _form.birthday = ''
    _form.employeeSex = 1
  }
}
// 校验身份证最后一位校验码
const checkIdCardChecksum = (idCard: string): boolean => {
  const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
  const checksums = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
  let sum = 0;

  for (let i = 0; i < 17; i++) {
    sum += parseInt(idCard[i], 10) * weights[i];
  }

  const mod = sum % 11;
  return checksums[mod] === idCard[17].toUpperCase();
}
const getear = (date: any) => {
  if (!date) {
    return '未知'
  }
  // 将输入的出生日期字符串转换为 Date 对象
  const birthDate = new Date(date);
  // 获取当前日期
  const today = new Date();

  // 计算年份差
  let year = today.getFullYear() - birthDate.getFullYear();

  // 检查是否未到生日
  const monthDifference = today.getMonth() - birthDate.getMonth();
  if (monthDifference < 0 || (monthDifference === 0 && today.getDate() < birthDate.getDate())) {
    year--;
  }
  return year;
}
//输入身份证号 获取性别和出生日期
const getIdInfo = (idCard: string) => {
  const info = {
    isValid: false,
    birthDate: '',
    gender: 1,//1男2女
  };

  // 验证身份证号码长度是否正确
  if (idCard.length !== 18) {
    return info;
  }

  // 提取出生日期
  const birthDateStr = idCard.substring(6, 14);
  const birthYear = parseInt(birthDateStr.substring(0, 4), 10);
  const birthMonth = parseInt(birthDateStr.substring(4, 6), 10) - 1; // 注意月份是从0开始的
  const birthDay = parseInt(birthDateStr.substring(6, 8), 10);

  // 验证日期是否有效
  const birthDate = new Date(birthYear, birthMonth, birthDay);
  if (
    birthDate.getFullYear() !== birthYear ||
    birthDate.getMonth() !== birthMonth ||
    birthDate.getDate() !== birthDay
  ) {
    return info;
  }

  // 提取性别
  const genderDigit = parseInt(idCard.charAt(16), 10);
  const gender = genderDigit % 2 === 0 ? 2 : 1;

  // 设置返回值
  info.isValid = true;
  info.birthDate = `${birthYear}-${String(birthMonth + 1).padStart(2, '0')}-${String(birthDay).padStart(2, '0')}`;
  info.gender = gender;

  return info;
}
const saveBtn = (form: any) => {
  let _form: any = {
    ...form,
    educationList: form.educationList.map((el: any) => ({
      employeeCode: form.employeeCode,
      educationCode: el.educationCode,
      school: el.school,
      graduationTime: el.graduationTime,
      major: el.major
    })),
    contactList: form.contactList.map((el: any) => ({
      employeeCode: form.employeeCode,
      contactName: el.contactName,
      contactRelationship: el.contactRelationship,
      contactPhone: el.contactPhone,
      remark: el.remark
    })),
    fileDataList: form.fileDataList
  }
  proxy.$api.Business.UpdateEmployeeBaseData(_form)
    .then((res: any) => {
      _sun()
    })
    .catch(() => { });

  function _sun() {
    proxy.$message('保存成功')
    // getForm()
    sendMsg('save', true);
    window.close();
  }
};
const getForm = () => {
  let _query: any = route.query
  data.loading = true
  if (_query.employeeID) {
    proxy.$api.Business.GetEmployeeDetail({
      queryBy: 1,//生产机台主键ID
      queryValue: _query.employeeID,//生产机台主键ID
    })
      .then((res: any) => {
        let _fileDataList: any = [
          {
            employeeCode: res.employeeCode,
            title: '身份证人像面',
            fileType: 0,
            fileUrl: '',
            fileOriginalName: '',
            filePreviewUrl: '',
          },
          {
            employeeCode: res.employeeCode,
            title: '身份证国徽面',
            fileType: 1,
            fileUrl: '',
            fileOriginalName: '',
            filePreviewUrl: '',
          },
          {
            employeeCode: res.employeeCode,
            title: '学历证书',
            fileType: 2,
            fileUrl: '',
            fileOriginalName: '',
            filePreviewUrl: '',
          },
          {
            employeeCode: res.employeeCode,
            title: '学位证书',
            fileType: 3,
            fileUrl: '',
            fileOriginalName: '',
            filePreviewUrl: '',
          },
          {
            employeeCode: res.employeeCode,
            title: '离职证明',
            fileType: 4,
            fileUrl: '',
            fileOriginalName: '',
            filePreviewUrl: '',
          },
          {
            employeeCode: res.employeeCode,
            title: '员工照片',
            fileType: 5,
            fileUrl: '',
            fileOriginalName: '',
            filePreviewUrl: '',
          },
        ]
        res.fileDataList.forEach((el: any) => {
          let _row = _fileDataList[el.fileType]
          _row.fileUrl = el.fileUrl
          _row.fileOriginalName = el.fileOriginalName
          _row.filePreviewUrl = el.filePreviewUrl
          _row.employeeFileDataID = el.employeeFileDataID
        });
        data.form = {
          ...res,
          fileDataList: _fileDataList
        }
        proxy.$message('获取成功')
        data.loading = false
      })
      .catch(() => {
      });
  }

};
import { getEmployeeType, getEmployeeState, getNation, getResidenceType, getPoliticsStatus, getMaritalStatus, getQualification } from '@/utils/optionsArr.ts';
onMounted(() => {
  getForm();
  getEmployeeType(options, 'employeeType');//获取员工类型
  getEmployeeState(options, 'employeeState');//获取员工状态
  getNation(options, 'nation');//获取民族
  getResidenceType(options, 'residenceType');//获取户籍类型
  getPoliticsStatus(options, 'politicsStatus');//获取政治面貌
  getMaritalStatus(options, 'maritalStatus');//获取婚姻状况
  getQualification(options, 'qualification');//获取学历
});
</script>
